#!/usr/bin/python2.7
from optparse import OptionParser
from appmain import AppMain
from curen.utils.classloader import load_class
import ConfigParser
import sys
import os
import os.path
import signal

def start(options):
    #0.load config 
    config = load_config(options)
    #1.config env
    config_env(options)    
    #2.load runner
    runner = load_runner(config)
    #3.load app
    app = load_app(config)
    #4.run app
    runner.run(app)

def config_env(options):
    cid = os.fork()
    if cid == 0:        
        print 'fork on ', os.getpid()
        if not os.path.exists('proc'):
            os.mkdir('proc')
        file = open('proc/%s.pid'%os.getpid(), 'w+')
        file.close()
        
        root = os.path.realpath(options.dir)
        os.chdir(root)
        sys.path.append(root)
    else:
        exit()
    
    
def load_app(config):
    exe = AppMain()
    app = exe.main(config)
    return app

def load_runner(config):
    clspath = config.get('server', 'runner')
    cls = load_class(clspath)
    runner = cls()
    runner.main(config)
    return runner

def load_config(options):
    config = ConfigParser.ConfigParser()
    cfgfile = open(os.path.basename(options.filename), 'r')
    config.readfp(cfgfile)
    return config
        

def stopall(options):
    def ff(arg, dirname, fnames):
        if dirname != 'proc':return
        files = filter(lambda x: x.rfind('pid') != -1, fnames)
        for f in files:
            pid = int(f[:f.rfind('.pid')])
            pids = os.popen("ps -ef | grep %s | grep -v grep | awk '{ print $2 }'" % pid).readlines()
            if len(pids) > 0:
                print 'stop', pid
                os.kill(pid, signal.SIGKILL)
            os.remove('%s/%s'%(dirname, f))
    os.path.walk('proc', ff, None)


def status(options):
    pass

def main():
    parser = OptionParser();
    parser.add_option("-f", "--file", dest="filename", help="config file", default="helloweb.conf")
    parser.add_option("-c", "--command", dest="cmd", help="start stopall status", default="start")
    parser.add_option("-d", "--dir", dest="dir", help="app dir", default=".")
    (options, args) = parser.parse_args()
    if options.cmd == 'start':
        start(options)
    elif options.cmd == 'stopall':
        stopall(options)
    elif options.cmd == 'restart':
        restart(options)
    elif options.cmd == 'status':
        status(options)
if __name__ == '__main__':
    main()
